<template>
  <div class="pie-chart-container">
    <!-- ECharts 图表容器 -->
    <div id="pie-chart" style="width: 100%; height: 260px;"></div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts';

onMounted(async () => {
  const chartDom = document.getElementById('pie-chart'); // 修改 id
  const myChart = echarts.init(chartDom);
  const colors = [
    '#ff9de2', '#8c82fc', '#b693fe', '#7effdb', '#f57170',
    '#10ddc2', '#15b7b9', '#b9d7ea', '#d6e6f2', '#fdffab',
  ];

  const option = {
    title: {
      text: '2018-2024年辆生产地区占比',
      top: 5,
      left: 'center',
      textStyle: {
        color: '#ffffff',
        fontFamily: 'YouYuan',
        fontSize: 18,
      },
    },
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'horizontal', // 设置图例排列方向为水平
      bottom: 0, // 设置图例在底部
      textStyle: {
        color: '#ffffff',
      },
      data: [],
    },
    series: [
      {
        type: 'pie',
        radius: '55%',
        top:'5%',
        data: [],
        itemStyle: {
          color: function (params) {
            return colors[params.dataIndex % colors.length]; // 按索引循环颜色
          },
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
   
  };

  myChart.setOption(option);

  try {
    const response = await axios.get('/api/queryAllMakeCountryTimes');
    const rawData = response.data.data;

    const data = rawData.map((item) => ({
      name: countryMap[item.brandCountry] || item.brandCountry,
      value: parseInt(item.count, 10),
    }));

    const updatedOption = {
      ...option,
      legend: {
        ...option.legend,
        data: data.map((item) => item.name),
      },
      series: [
        {
          ...option.series[0],
          data,
        },
      ],
    };

    myChart.setOption(updatedOption);
  } catch (error) {
    console.error('Error fetching data: ', error);
  }
});

const countryMap = {
  China: '中国',
  'United States': '美国',
  Germany: '德国',
  Japan: '日本',
  'South Korea': '韩国',
  'Czech Republic': '捷克',
  France: '法国',
  Sweden: '瑞典',
  'United Kingdom': '英国',
  Italy: '意大利',
};
</script>

<style scoped>
.pie-chart-container {
  width: 100%;
  height: 100%;
  padding: 10px;
}

#pie-chart {
  width: 100%;
  height: 250px;
}
</style>
